<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button
          size="mini"
          type="primary"
          @click="addDialog"
        >添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="roleList">
        <!-- 放置列 -->
        <el-table-column align="center" width="200" label="角色" prop="name">
          <template #default="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.name"
              size="mini"
            />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" width="200" label="启用" prop="state">
          <template #default="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>{{ row.state === 1 ? "已启用" : "未启用" }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="描述" prop="description">
          <template #default="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.description"
              type="textarea"
            />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <template v-if="row.isEdit">
              <el-button
                size="mini"
                type="primary"
                @click="formDialog.methods.updateRole(row)"
              >确定</el-button>
              <el-button
                size="mini"
                @click="formDialog.methods.btnEditCancel(row)"
              >取消</el-button>
            </template>
            <template v-else>
              <el-button
                size="mini"
                type="text"
                @click="btnPreMission(row.id)"
              >分配权限</el-button>
              <el-button
                size="mini"
                type="text"
                @click="row.isEdit = true"
              >编辑</el-button>
              <el-button
                size="mini"
                type="text"
                @click="del(row)"
              >删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height: 60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          :page-size="params.pagesize"
          :total="total"
          layout="prev, pager, next"
          @current-change="currentChange"
        />
      </el-row>
    </div>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="showPremDialog">
      <el-tree
        ref="permTree"
        check-strictly
        :default-checked-keys="checkedKey"
        node-key="id"
        :data="permissionData"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button
            type="primary"
            size="mini"
            @click="btnPermissionOK"
          >确定</el-button>
          <el-button size="mini">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 添加弹层 -->
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
      <!-- 表单内容 -->
      <el-form
        ref="addForm"
        :model="formDialog.data"
        :rules="formDialog.rules"
        label-width="120px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="formDialog.data.name"
            style="width: 300px"
            size="mini"
          />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch
            v-model="formDialog.data.state"
            :active-value="1"
            :inactive-value="0"
            size="mini"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="formDialog.data.description"
            type="textarea"
            :rows="3"
            style="width: 300px"
            size="mini"
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button
                type="primary"
                size="mini"
                @click="formDialog.methods.ok"
              >确定</el-button>
              <el-button
                size="mini"
                @click="showDialog = false"
              >取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, editRole, delRole } from '@/api/role'
import { getPermissionList, getRoleInfoById, assignPrem } from '@/api/permission'
export default {
  name: 'RolePage',
  data() {
    return {
      // 分配权限id
      btnPreMissionId: '',
      checkedKey: [],
      permissionData: [],
      showPremDialog: false,
      roleList: [],
      formDialog: {
        data: {
          name: '',
          state: 0,
          description: ''
        },
        rules: {
          name: [{ required: true, message: '请输入角色名称' }],
          description: [{ required: true, message: '请输入角色描述' }]
        },
        methods: {
          updateRole: async(row) => {
            if (row.editRow.name && row.editRow.description) {
              await editRole(row.editRow)
              this.$message.success('修改角色成功')
              // row.isEdit = false
              this.getList()
            }
          },
          btnEditCancel: (row) => {
            row.isEdit = false
            row.editRow = {
              ...row
            }
          },
          ok: async() => {
            await this.$refs.addForm.validate()
            await addRole(this.formDialog.data)
            this.$message.success('新增角色成功')
            this.showDialog = false
            this.getList()
          }
        }
      },
      params: {
        page: 1,
        pagesize: 10
      },
      total: 0,
      showDialog: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async btnPermissionOK() {
      // 获取用户选中权限节点id
      const check = this.$refs.permTree.getCheckedKeys()
      // console.log(check)
      await assignPrem({
        id: this.btnPreMissionId,
        permIds: check
      })
      this.$message.success('分配权限成功')
      this.showPremDialog = false
    },
    async btnPreMission(id) {
      const res = await getPermissionList()

      // 声明一个找儿子的函数
      function getChildren(id) {
        return res.filter((v) => v.pid === id)
      }
      //
      res.forEach((v) => {
        if (getChildren(v.id).length) {
          v.children = getChildren(v.id)
        }
      })

      // 将一级节点找出来
      this.btnPreMissionId = id
      this.checkedKey = []
      const list = res.filter((v) => v.pid === 0)
      this.permissionData = list
      const checked = await getRoleInfoById(id)
      this.checkedKey = checked.permIds
      this.showPremDialog = true
    },
    async del(row) {
      await this.$confirm(`您确定要删除：${row.name} 吗？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await delRole(row.id)
      this.$message.success('删除角色成功')
      this.getList()
    },
    addDialog() {
      this.$refs.addForm?.resetFields()
      this.showDialog = true
    },
    currentChange(current) {
      this.params.page = current
      this.getList()
    },
    async getList() {
      const res = await getRoleList(this.params)
      this.roleList = res.rows
      this.total = res.total
      this.roleList.forEach((item) => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description,
          id: item.id
        })
      })
      console.log(this.roleList)
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
